<script lang="ts" setup>
import { getById, urls, getReadonly, reSetDialogModel, insertOne, updateOne } from '@/index';
import type { DialogModel, DictionaryType, Dictionary, User } from '@/index.d';
import type { FormInstance } from 'element-plus';

const props = defineProps({
  //顺序号可以接受的最大值
  maxSequence: Number
});

const dialogModel = defineModel<DialogModel<Dictionary>>('dialogModel', {
  type: Object,
  required: true
});

const readonly = getReadonly(dialogModel.value);

const currentDictionaryType = defineModel<DictionaryType>('currentDictionaryType', {
  type: Object,
  required: true
});

const formData = reactive<Dictionary>({
  tenant: 0,
  typeText: '',
  typeCode: '',
  label: '',
  value: '',
  sequence: 0
});

const setFormData = (value: Dictionary) => {
  formData.id = value.id;
  formData.typeText = value.typeText;
  formData.typeCode = value.typeCode;
  formData.label = value.label;
  formData.value = value.value;
  formData.creator = value.creator;
  formData.createTime = value.createTime;
  formData.updater = value.updater;
  formData.updateTime = value.updateTime;
  formData.sequence = value.sequence;
};

const reSetFormData = () => {
  reSetDialogModel(dialogModel);
  formData.id = 0;
  formData.sequence = 0;
  delete formData.label;
  delete formData.value;
  delete formData.creator;
  delete formData.creator;
  delete formData.createTime;
  delete formData.updater;
  delete formData.updateTime;
};

watch(
  () => dialogModel.value.visible,
  (data: boolean) => {
    if (data) {
      formData.id = dialogModel.value.id as number;
      //当打开窗口时，将从租户预设到表单中
      //当打开窗口时，将从字典类型树传递过来的值预设到表单中
      formData.tenant = currentDictionaryType.value.tenant;
      formData.typeText = currentDictionaryType.value.typeText;
      formData.typeCode = currentDictionaryType.value.typeCode;
      //字典值顺序可以设置的最大值
      formData.sequence = (props.maxSequence as number) + 1;
    } else {
      reSetFormData();
    }
  }
);

//让你label和value的值默认保持一致
watch(
  () => formData.label as string,
  (value: string) => (formData.value = value)
);

// 监控id的变化，当id为0，为新增窗口，无需从数据库取值填充，当id不为0时，为更新或者查看窗口，从数据库取值进行填充
watch(
  () => dialogModel.value.id,
  async value => {
    if (value !== 0 && value !== undefined) {
      try {
        const res = (await getById(urls.dictionary, value)) as Dictionary;
        setFormData(res);
      } catch (error) {
        ElMessage.error('获取失败，错误信息是：' + error);
      }
    }
  },
  {
    immediate: true
  }
);

const formRef = ref<FormInstance>();

const formRules = {
  label: [
    { required: true, message: '字典选项不能为空', trigger: 'blur' },
    { max: 10, message: '字典选项长度应为小于10位', trigger: 'blur' }
  ]
};

const save = async () => {
  const res = await insertOne<Dictionary>(urls.dictionary, formData);
  if (res) {
    setFormData(res);
    dialogModel.value.id = res.id as number;
    dialogModel.value.type = 'update';
    dialogModel.value.change = true;
  }
};

const update = async () => {
  const tempFormData: Dictionary = {
    id: formData.id,
    tenant: formData.tenant,
    typeText: formData.typeText,
    typeCode: formData.typeCode,
    label: formData.label,
    value: formData.value,
    sequence: formData.sequence
  };
  const res = await updateOne<Dictionary>(urls.dictionary, tempFormData);
  if (res) {
    dialogModel.value.change = true;
    formData.updater = res.updater;
    formData.updateTime = res.updateTime;
  }
};

const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      dialogModel.value.id === 0 ? save() : update();
    }
  });
};
</script>
<template>
  <hq-dialog-detail
    v-if="dialogModel.visible"
    v-model:dialog-model="dialogModel"
    @submit="handleSubmit(formRef)"
    :operation="formData"
    operate-record
  >
    <el-card shadow="hover">
      <template #header>基本信息</template>
      <template #default>
        <el-form :model="formData" ref="formRef" status-icon label-suffix="：" :rules="formRules">
          <el-row :gutter="5">
            <hq-col>
              <el-form-item label="序号" prop="id">
                <el-input v-model.number="formData.id" readonly />
              </el-form-item>
            </hq-col>
            <hq-col>
              <el-form-item label="租户" prop="tenant">
                <HqCascaderDepartment :current="formData.tenant" disabled />
              </el-form-item>
            </hq-col>
            <hq-col>
              <el-form-item label="字典类型" prop="typeText">
                <el-input v-model.number="formData.typeText" readonly />
              </el-form-item>
            </hq-col>
            <hq-col>
              <el-form-item label="字典选项" prop="label">
                <el-input
                  v-model.trim="formData.label"
                  show-word-limit
                  :maxlength="10"
                  clearable
                  :readonly="readonly.updateForbidden.value"
                />
              </el-form-item>
            </hq-col>
            <hq-col>
              <el-form-item label="字典值顺序" prop="sequence">
                <el-input v-model.number="formData.sequence" readonly />
              </el-form-item>
            </hq-col>
            <hq-col v-show="false">
              <el-form-item label="租户" prop="tenant">
                <el-input v-model.number="formData.tenant" readonly />
              </el-form-item>
            </hq-col>
            <hq-col v-show="false">
              <el-form-item label="字典类型Code" prop="typeCode">
                <el-input v-model.number="formData.typeCode" readonly />
              </el-form-item>
            </hq-col>
            <hq-col v-show="false">
              <el-form-item label="字典值" prop="value">
                <el-input v-model.trim="formData.value" readonly />
              </el-form-item>
            </hq-col>
          </el-row>
        </el-form>
      </template>
    </el-card>
  </hq-dialog-detail>
</template>
<style lang="scss" scoped></style>
